<?php
/**
 * TomatoCMS
 *
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@tomatocms.com so we can send you a copy immediately.
 *
 * @copyright    Copyright (c) 2009-2010 TIG Corporation (http://www.tig.vn)
 * @license        http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @version     $Id: Category.php 2870 2010-05-17 03:04:13Z quanvo $
 * @since        2.0.5
 */

class Shop_Models_Dao_Pdo_Mysql_Product    extends Tomato_Model_Dao
    implements Shop_Models_Interface_Product
{
    public function convert($entity)
    {
        return new Shop_Models_Product($entity);
    }
	/*
		Get production cost with bundle and not bundle
	*/
	public function getProductionCost($product_id){		
		$product 		= $this->getProductById($product_id);
		// chi phi san xuat cua 1 san pham nay, chua tinh bundle
		$sum_cost   	= $product->product_shipping_price; 
		
		if($product->product_bundle == 1){// san pham nay` la bundle
			$product_product_id_chain	= trim($product->product_product_id_chain,',');			
			$arr_product_id_chain       = explode(',',$product_product_id_chain);
			if(count($arr_product_id_chain)>0){
			  foreach($arr_product_id_chain as $item_chain){
				$product_chain_Obj    = $this->getProductById($product_id);
				$sum_cost   		 += $product_chain_Obj->product_shipping_price;
			  }
			}
		}
		return $sum_cost;
	}
	
    public function getProductContentById($id)
    {
        $select = $this->_conn
                        ->select()
                        ->from(array('c' => $this->_prefix.'shop_product_content'));
        $select->where('c.product_id = ?', $id);
        $rs = $select->query()->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }

    public function findAllProducts($enterprise_id = null)
    {
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'));
        $select->where('p.product_bundle != ?', 1);
        if(null != $enterprise_id){
            $select->where("p.enterprise_id = ?", $enterprise_id);
        }
        $rs = $select->query()->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }
    public function add($product)
    {
		$product_product_id_chain	= trim($product->product_product_id_chain,',');
		$product_product_id_chain = ','.$product_product_id_chain.',';
		$product->product_product_id_chain = $product_product_id_chain;	
        $data = array(
            'product_admin_name'        => $product->product_admin_name,
            'category_id'                   => $product->category_id,
            'account_id'                   => $product->account_id,
            'product_price'             => $product->product_price,
            'product_price_currency'    => $product->product_price_currency,
            'product_status_of_delivery'=> $product->product_status_of_delivery,
            'product_quantity'             => $product->product_quantity,
            'product_quantity_mode'     => $product->product_quantity_mode,
            'product_status'             => $product->product_status,
            'product_created_date'         => $product->product_created_date,
            'product_modified_date'     => $product->product_modified_date,
            'production_duration'         => $product->production_duration,
            'product_bundle'             => $product->product_bundle,
            'product_product_id_chain'     => $product->product_product_id_chain,
            'product_shipping_price'    => $product->product_shipping_price,
            'product_image'                => $product->product_image,
            'enterprise_id'                => $product->enterprise_id,
            'product_shipping_price_1'    => $product->product_shipping_price_1,
            'product_shipping_price_2'    => $product->product_shipping_price_2,
        );
        $this->_conn->insert($this->_prefix.'shop_product', $data);
        return $this->_conn->lastInsertId($this->_prefix.'shop_product');
    }

    public function find($offset, $count, $exp = null){
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'))
                        ->joinLeft(array('pc' => $this->_prefix.'shop_product_content'), "p.product_id = pc.product_id AND pc.language_code = '{$this->_lang}'", array('product_content_id', 'language_code', 'product_content_name', 'slug' => 'product_content_friendly_url', 'product_content_description'))
                        ;
        if ($exp) {
            if (isset($exp['category_id'])) {
                $select->where("p.category_id LIKE '%,".$exp['category_id'].",%'");
            }
            if (isset($exp['product_status'])) {
                $select->where('p.product_status = ?', $exp['product_status']);
            }
            if (isset($exp['keyword'])) {
                $select->where("p.product_admin_name LIKE '%".addslashes($exp['keyword'])."%'");
            }
            if (isset($exp['enterprise_id'])) {
                $select->where("p.enterprise_id = ?", $exp['enterprise_id']);
            }
            if (isset($exp['frontend_active']) || isset($exp['deleted']) ) {
                $select->joinLeft(array('e' => $this->_prefix.'enterprise'), "p.enterprise_id = e.id", array());
				if (isset($exp['frontend_active']))
					$select->where("e.frontend_active = ?", $exp['frontend_active']);
				if (isset($exp['deleted']))
					$select->where("e.deleted != 1");					   
            }
			if(isset($exp['product_status'])){
				$select->where("p.product_status = ?",$exp['product_status']);
			}
			// san pham nay` co phai la bundle hay ko?
			if(isset($exp['product_bundle'])){
				$select->where("p.product_bundle = ?",$exp['product_bundle']);
			}
			
			// bundle is string 1,2,3,4
			// chi? can` co o find, ko can` co o count -> ko dung` j den,cho them dieu kien nay` vao la` 
			// de liet ke danh sach san pham bundle trong tab mo ta
			if(isset($exp['bundle'])){
				$select->where("p.product_id IN (".$exp['bundle'].")");
			}
        }
        $select->order('p.product_id DESC')
                ->limit($count, $offset);
        $rs = $select->query()->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }

    public function count($exp = null)
    {
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'), array('num_product' => 'COUNT(*)'));
        if ($exp) {
            if (isset($exp['frontend_active']) || isset($exp['deleted']) ) {
                $select->joinLeft(array('e' => $this->_prefix.'enterprise'), "p.enterprise_id = e.id", array());
				if (isset($exp['frontend_active']))
					$select->where("e.frontend_active = ?", $exp['frontend_active']);
				if (isset($exp['deleted']))
					$select->where("e.deleted != 1");					   
            }		
            if (isset($exp['category_id'])) {
                $select->where("p.category_id LIKE '%,".$exp['category_id'].",%'");
            }
            if (isset($exp['product_status'])) {
                $select->where('p.product_status = ?', $exp['product_status']);
            }
            if (isset($exp['keyword'])) {
                $select->where("p.product_admin_name LIKE '%".addslashes($exp['keyword'])."%'");
            }
            if (isset($exp['enterprise_id'])) {
                $select->where("p.enterprise_id = ?", $exp['enterprise_id']);
            }
			if(isset($exp['product_status'])){
				$select->where("p.product_status = ?",$exp['product_status']);
			}	
			// san pham nay` co phai la bundle hay ko?
			if(isset($exp['product_bundle'])){
				$select->where("p.product_bundle = ?",$exp['product_bundle']);
			}			
        }
        $row = $select->query()->fetch();
        return $row->num_product;
    }
    public function getProductById($id , $language_code = null){
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'));
        if($language_code){
            $select->joinLeft(array('pc' => $this->_prefix.'shop_product_content'), "p.product_id = pc.product_id AND language_code = '{$language_code}'", array('product_content_id', 'language_code', 'product_content_name', 'slug'=>'product_content_friendly_url','product_content_description'));
        }
        $select->where('p.product_id = ?', $id);
        $select->limit(1);
        $row = $select->query()->fetchAll();
        $products = new Tomato_Model_RecordSet($row, $this);
        return (count($products) == 0) ? null : $products[0];
    }
    public function edit($product, $product_id){
		$product_product_id_chain	= trim($product->product_product_id_chain,',');
		$product_product_id_chain = ','.$product_product_id_chain.',';
		$product->product_product_id_chain = $product_product_id_chain;	
        $data = array(
            'product_admin_name'        => $product->product_admin_name,
            'category_id'                   => $product->category_id,
            'account_id'                   => $product->account_id,
            'product_price'             => $product->product_price,
            'product_price_currency'    => $product->product_price_currency,
            'product_status_of_delivery'=> $product->product_status_of_delivery,
            'product_quantity'             => $product->product_quantity,
            'product_quantity_mode'     => $product->product_quantity_mode,
            'product_status'             => $product->product_status,
            'product_modified_date'     => $product->product_modified_date,
            'product_bundle'             => $product->product_bundle,
            'product_product_id_chain'     => $product->product_product_id_chain,
            'product_shipping_price'    => $product->product_shipping_price,
            'product_image'                => $product->product_image,
            'enterprise_id'                => $product->enterprise_id,
            'product_shipping_price_1'    => $product->product_shipping_price_1,
            'product_shipping_price_2'    => $product->product_shipping_price_2,
        );
        $where[] = 'product_id = '.$this->_conn->quote($product_id);
        $this->_conn->update($this->_prefix.'shop_product', $data, $where);
    }
    public function getAttributeByCategoryId($category_id){
        $select = $this->_conn
                        ->select()
                        ->from(array('at' => $this->_prefix.'shop_attribute_type'))
                        ->where("category_id like '%,{$category_id},%'")
                        ;
        $rs = $select->query()->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }
    public function getAttributeContentByAttributeIdLanguage($attribute_id, $language_code){
        $select = $this->_conn
                        ->select()
                        ->from(array('atc' => $this->_prefix.'shop_attribute_type_content'))
                        ->where("attribute_type_id = $attribute_id AND language_code = '$language_code'")
                        ;
        $rs = $select->query()->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }
    public function getAttributeContentByAttributeId($attribute_id){
        $select = $this->_conn
                        ->select()
                        ->from(array('atc' => $this->_prefix.'shop_attribute_type_content'))
                        ->where("attribute_type_id = ?",$attribute_id)
                        ;
        $rs = $select->query()->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }

    public function getCurrency()
    {
        $select = $this->_conn
                        ->select()
                        ->from(array('c' => $this->_prefix.'currency'));
        $rs = $select->query()->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }
    public function delete($product_id){
        $where[] = 'product_id = '.$this->_conn->quote($product_id);
        return $this->_conn->delete($this->_prefix.'shop_product', $where);
    }
    public function updateProductionDuration($product, $product_id){
        $data = array(
            'production_duration'        => $product->production_duration,
        );
        $where[] = 'product_id = '.$this->_conn->quote($product_id);
        $this->_conn->update($this->_prefix.'shop_product', $data, $where);
    }

    /*--------------------------------Front-end function---------------------------------*/

    public function getPById($exp = null, $offset = null, $count = null){
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'))
                        ->joinLeft(array('pc' => $this->_prefix.'shop_product_content'), "p.product_id = pc.product_id AND pc.language_code = '{$this->_lang}'", array('product_content_id', 'language_code', 'product_content_name', 'slug' => 'product_content_friendly_url', 'product_content_description'))
                        ->where('p.product_status = ?', 1)
                        ;
        if ($exp) {
            if (isset($exp['enterprise'])) {
                $select->where($exp['enterprise']);
            }
            if (isset($exp['frontend_active']) || isset($exp['deleted']) ) {
                $select->joinLeft(array('e' => $this->_prefix.'enterprise'), "p.enterprise_id = e.id", array());
				if (isset($exp['frontend_active']))
					$select->where("e.frontend_active = ?", $exp['frontend_active']);
				if (isset($exp['deleted']))
					$select->where("e.deleted != 1");					   
            }			
        }
        $select->order('p.product_id DESC');
        if(null != $offset){
            $select->limit($count, $offset);
        }
        $rs = $select->query()->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }

    public function checkFile($path, $file, $name = '_square'){
        $new_file = null;
        if(is_file($path)){
            $pathinfo = pathinfo($path);
            $arrEx = explode('_',$file);
            $forReplace = $arrEx[count($arrEx)-1];
            $new_file = str_replace('_'.$forReplace, $name.'.'.$pathinfo['extension'], $file);
        }
        return $new_file;
    }

    public function catOfEnt($id = null){
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'), array('category_id'))
                        ->joinInner(array('c' => $this->_prefix.'shop_category'), "p.category_id like concat('%,',c.category_id,',%')", array('category_id', 'category_admin_name', 'category_image'))
                        ->joinLeft(array('cc' => $this->_prefix.'shop_category_content'), "c.category_id = cc.category_id AND cc.language_code = '{$this->_lang}'", array('category_content_id', 'language_code', 'category_content_name', 'slug'=>'category_content_friendly_url', 'category_content_description'))
                        ->where('p.product_status = ?', 1)
                        ;
                 if(null != $id){
                 $select->where('p.enterprise_id = ?', $id);
                 }
        $rs = $select->query()->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }

    public function getMarketData($id){
        $select = $this->_conn
                        ->select()
                        ->from(array('md' => $this->_prefix.'shop_product_market_data'))
                        ->where('md.product_id = ?', $id)
                        ->limit(1);
        $row = $select->query()->fetchAll();
        $products = new Tomato_Model_RecordSet($row, $this);
        return (count($products) == 0) ? null : $products[0];
    }

    public function addMarketData($product){
        $data = array(
            'product_id'  => $product->product_id,
            'category_id' => $product->category_id
        );
        if(isset($product->view_count)){
            $data['view_count'] = $product->view_count;
        }
        if(isset($product->buy_count)){
            $data['buy_count'] = $product->buy_count;
        }
        return $this->_conn->insert($this->_prefix.'shop_product_market_data', $data);
    }

    public function updateMarketData($product){
        $where[] = "product_id = {$product->product_id}";
        if(isset($product->view_count)){
            $sql = "UPDATE `{$this->_prefix}shop_product_market_data` SET `view_count` = `view_count`+{$product->view_count} WHERE `product_id` = {$product->product_id}";
        }
        if(isset($product->buy_count)){
            $sql = "UPDATE `{$this->_prefix}shop_product_market_data` SET `buy_count` = `buy_count`+{$product->buy_count} WHERE `product_id` = {$product->product_id}";
        }
        return $this->_conn->query($sql);
    }

    public function getMostViewed($count, $id = null){
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'))
                        ->joinLeft(array('pc' => $this->_prefix.'shop_product_content'), "p.product_id = pc.product_id AND pc.language_code = '{$this->_lang}'", array('product_content_id', 'language_code', 'product_content_name', 'slug' => 'product_content_friendly_url', 'product_content_description'))
                        ->joinLeft(array('md' => $this->_prefix.'shop_product_market_data'), "p.product_id = md.product_id", array())
						->joinLeft(array('e' => $this->_prefix.'enterprise'), "p.enterprise_id = e.id", array());
                        if($id){
                            $select->where("p.category_id LIKE '%,".$id.",%'");
                        }
						$select->where("p.product_status = 1 ");
						$select->where("e.frontend_active = 1 ");
						$select->where("e.deleted != 1 ");
                        $select->limit($count, 0)
                                ->order('md.view_count DESC')
                                ->group("p.product_id")
                                ;
        $rs = $select->query()->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }

    public function getMostBuy($count, $id = null){
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'))
                        ->joinLeft(array('pc' => $this->_prefix.'shop_product_content'), "p.product_id = pc.product_id AND pc.language_code = '{$this->_lang}'", array('product_content_id', 'language_code', 'product_content_name', 'slug' => 'product_content_friendly_url', 'product_content_description'))
                        ->joinInner(array('md' => $this->_prefix.'shop_product_market_data'), "p.product_id = md.product_id", array())
						->joinLeft(array('e' => $this->_prefix.'enterprise'), "p.enterprise_id = e.id", array())
                        ->where('md.buy_count is not null');
                        if($id){
                            $select->where('md.category_id = ?', $id);
                        }
						$select->where("p.product_status = 1 ");
						$select->where("e.frontend_active = 1 ");
						$select->where("e.deleted != 1 ");
						
                        $select->limit($count, 0)
                                ->order('md.buy_count DESC')
                                ->group("p.product_id");
        $rs = $select->query()->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }

    public function getAdvertise($count, $id = 0){
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'))
                        ->joinLeft(array('pc' => $this->_prefix.'shop_product_content'), "p.product_id = pc.product_id AND pc.language_code = '{$this->_lang}'", array('product_content_id', 'language_code', 'product_content_name', 'slug' => 'product_content_friendly_url', 'product_content_description'))
                        ->joinInner(array('md' => $this->_prefix.'shop_product_market_data'), "p.product_id = md.product_id", array())
						->joinLeft(array('e' => $this->_prefix.'enterprise'), "p.enterprise_id = e.id", array())
                        ->where('md.advertise = ?',1);
						$select->where("e.frontend_active = 1 ");
						$select->where("e.deleted != 1 ");
                        $select->where('md.category_id = ?', $id)
                                ->limit($count, 0)
                                ->group("p.product_id");
        $rs = $select->query()->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }

    public function search($offset, $count, $exp = null, $related = false){
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'))
                        ->joinLeft(array('pc' => $this->_prefix.'shop_product_content'), "p.product_id = pc.product_id AND pc.language_code = '{$this->_lang}'", array('product_content_id', 'language_code', 'product_content_name', 'slug' => 'product_content_friendly_url', 'product_content_description'))
                        ;
        if ($exp) {
            if (isset($exp['frontend_active']) || isset($exp['deleted']) ) {
                $select->joinLeft(array('e' => $this->_prefix.'enterprise'), "p.enterprise_id = e.id", array());
				if (isset($exp['frontend_active']))
					$select->where("e.frontend_active = ?", $exp['frontend_active']);
				if (isset($exp['deleted']))
					$select->where("e.deleted != 1");					   
            }		
            if (isset($exp['category_id'])) {
                $select->where("p.category_id LIKE '%,".$exp['category_id'].",%'");
            }
            if (isset($exp['product_status'])) {
                $select->where('p.product_status = ?', $exp['product_status']);
            }
            if($related){
                if (isset($exp['keyword'])) {
                    $select->where("match(p.product_admin_name, pc.product_content_name, pc.product_content_description) against('{$exp['keyword']}' IN BOOLEAN MODE)");
                }
                if (isset($exp['strPId'])) {
                    $select->where("'{$exp['strPId']}' not like concat('%,',p.product_id,',%')");
                }
            }
            else{
                if (isset($exp['keyword'])) {
                    $select->where("p.product_admin_name LIKE '%".addslashes($exp['keyword'])."%' OR pc.product_content_name LIKE'%".addslashes($exp['keyword'])."%' OR pc.product_content_description LIKE '%".addslashes($exp['keyword'])."%'");
                }
            }
            if (isset($exp['enterprise_id'])) {
                $select->where("p.enterprise_id = ?", $exp['enterprise_id']);
            }
        }
        $select->order('p.product_id DESC')
                ->limit($count, $offset);
        $rs = $select->query()->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }

    public function searchcount($exp = null, $related = false)
    {
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'), array('num_product' => 'COUNT(*)'))
                        ->joinLeft(array('pc' => $this->_prefix.'shop_product_content'), "p.product_id = pc.product_id AND pc.language_code = '{$this->_lang}'", array())
                        ;

        if ($exp) {
            if (isset($exp['frontend_active']) || isset($exp['deleted']) ) {
                $select->joinLeft(array('e' => $this->_prefix.'enterprise'), "p.enterprise_id = e.id", array());
				if (isset($exp['frontend_active']))
					$select->where("e.frontend_active = ?", $exp['frontend_active']);
				if (isset($exp['deleted']))
					$select->where("e.deleted != 1");					   
            }		
            if (isset($exp['category_id'])) {
                $select->where("p.category_id LIKE '%,".$exp['category_id'].",%'");
            }
            if (isset($exp['product_status'])) {
                $select->where('p.product_status = ?', $exp['product_status']);
            }
            if($related){
                if (isset($exp['keyword'])) {
                    $select->where("match(p.product_admin_name, pc.product_content_name, pc.product_content_description) against('{$exp['keyword']}' IN BOOLEAN MODE)");
                }
                if (isset($exp['strPId'])) {
                    $select->where("'{$exp['strPId']}' not like concat('%,',p.product_id,',%')");
                }
            }
            else{
                if (isset($exp['keyword'])) {
                    $select->where("p.product_admin_name LIKE '%".addslashes($exp['keyword'])."%' OR pc.product_content_name LIKE'%".addslashes($exp['keyword'])."%' OR pc.product_content_description LIKE '%".addslashes($exp['keyword'])."%'");
                }
            }
            if (isset($exp['enterprise_id'])) {
                $select->where("p.enterprise_id = ?", $exp['enterprise_id']);
            }
        }
        $row = $select->query()->fetch();
        return $row->num_product;
    }

    public function advanced($offset, $count, $exp = null, $related = false){
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'))
                        ->joinLeft(array('pc' => $this->_prefix.'shop_product_content'), "p.product_id = pc.product_id AND pc.language_code = '{$this->_lang}'", array('product_content_id', 'language_code', 'product_content_name', 'slug' => 'product_content_friendly_url', 'product_content_description'))
                        ->joinLeft(array('pa' => $this->_prefix.'shop_product_attribute'), "p.product_id = pa.product_id ", array('att_product_id' => 'product_id', 'attribute_type_id', 'value_type_id_chain'))
                        ;
        if ($exp) {
            if (isset($exp['frontend_active']) || isset($exp['deleted']) ) {
                $select->joinLeft(array('e' => $this->_prefix.'enterprise'), "p.enterprise_id = e.id", array());
				if (isset($exp['frontend_active']))
					$select->where("e.frontend_active = ?", $exp['frontend_active']);
				if (isset($exp['deleted']))
					$select->where("e.deleted != 1");					   
            }		
            if (isset($exp['category_id'])) {
                $select->where("p.category_id LIKE '%,".$exp['category_id'].",%'");
            }
            if (isset($exp['product_status'])) {
                $select->where('p.product_status = ?', $exp['product_status']);
            }
            if($related){
                if (isset($exp['keyword'])) {
                    $select->where("match(p.product_admin_name, pc.product_content_name, pc.product_content_description) against('{$exp['keyword']}' IN BOOLEAN MODE)");
                }
                if (isset($exp['strPId'])) {
                    $select->where("'{$exp['strPId']}' not like concat('%,',p.product_id,',%')");
                }
            }
            else{
                if (isset($exp['keyword'])) {
                    $select->where("p.product_admin_name LIKE '%".addslashes($exp['keyword'])."%' OR pc.product_content_name LIKE'%".addslashes($exp['keyword'])."%' OR pc.product_content_description LIKE '%".addslashes($exp['keyword'])."%'");
                }
            }
            if (isset($exp['attribute_id'])) {
                $select->where("pa.attribute_type_id = ?", $exp['attribute_id']);
            }
            if (isset($exp['value'])) {
                $select->where("pa.value_type_id_chain REGEXP '{$exp['value']}'");
            }
            if (isset($exp['enterprise_id'])) {
                $select->where("p.enterprise_id = ?", $exp['enterprise_id']);
            }
        }
        $select->group('p.product_id')
               ->order('p.product_id DESC')
               ->limit($count, $offset);
               //echo $select;
        $rs = $select->query()->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }

    public function advancedcount($exp = null, $related = false)
    {
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'), array('product_id'))
                        ->joinLeft(array('pc' => $this->_prefix.'shop_product_content'), "p.product_id = pc.product_id AND pc.language_code = '{$this->_lang}'", array())
                        ->joinLeft(array('pa' => $this->_prefix.'shop_product_attribute'), "p.product_id = pa.product_id ", array())
                        ;

        if ($exp) {
            if (isset($exp['frontend_active']) || isset($exp['deleted']) ) {
                $select->joinLeft(array('e' => $this->_prefix.'enterprise'), "p.enterprise_id = e.id", array());
				if (isset($exp['frontend_active']))
					$select->where("e.frontend_active = ?", $exp['frontend_active']);
				if (isset($exp['deleted']))
					$select->where("e.deleted != 1");					   
            }		
            if (isset($exp['category_id'])) {
                $select->where("p.category_id LIKE '%,".$exp['category_id'].",%'");
            }
            if (isset($exp['product_status'])) {
                $select->where('p.product_status = ?', $exp['product_status']);
            }
            if($related){
                if (isset($exp['keyword'])) {
                    $select->where("match(p.product_admin_name, pc.product_content_name, pc.product_content_description) against('{$exp['keyword']}' IN BOOLEAN MODE)");
                }
                if (isset($exp['strPId'])) {
                    $select->where("'{$exp['strPId']}' not like concat('%,',p.product_id,',%')");
                }
            }
            else{
                if (isset($exp['keyword'])) {
                    $select->where("p.product_admin_name LIKE '%".addslashes($exp['keyword'])."%' OR pc.product_content_name LIKE'%".addslashes($exp['keyword'])."%' OR pc.product_content_description LIKE '%".addslashes($exp['keyword'])."%'");
                }
            }
            if (isset($exp['attribute_id'])) {
                $select->where("pa.attribute_type_id = ?", $exp['attribute_id']);
            }
            if (isset($exp['value'])) {
                $select->where("pa.value_type_id_chain REGEXP '{$exp['value']}'");
            }
            if (isset($exp['enterprise_id'])) {
                $select->where("p.enterprise_id = ?", $exp['enterprise_id']);
            }
        }
        $select->group('p.product_id');
        $rs = $select->query()->fetchAll();
        return count($rs);
    }

    public function frontFind($offset, $count, $exp = null){
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'))
                        ->joinLeft(array('pc' => $this->_prefix.'shop_product_content'), "p.product_id = pc.product_id AND pc.language_code = '{$this->_lang}'", array('product_content_id', 'language_code', 'product_content_name', 'slug' => 'product_content_friendly_url', 'product_content_description'))
                        ;
        if ($exp) {
            if (isset($exp['frontend_active']) || isset($exp['deleted']) ) {
                $select->joinLeft(array('e' => $this->_prefix.'enterprise'), "p.enterprise_id = e.id", array());
				if (isset($exp['frontend_active']))
					$select->where("e.frontend_active = ?", $exp['frontend_active']);
				if (isset($exp['deleted']))
					$select->where("e.deleted != 1");					   
            }		
            if (isset($exp['strcat_id'])) {
                $select->where("'{$exp['strcat_id']}' LIKE concat('%',p.category_id,'%')");
            }
            if (isset($exp['product_status'])) {
                $select->where('p.product_status = ?', $exp['product_status']);
            }
            if (isset($exp['keyword'])) {
                $select->where("p.product_admin_name LIKE '%".addslashes($exp['keyword'])."%'");
            }
            if (isset($exp['enterprise_id'])) {
                $select->where("p.enterprise_id = ?", $exp['enterprise_id']);
            }
        }
        $select->order('p.product_id DESC')
                ->limit($count, $offset);
        $rs = $select->query()->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }

    public function frontCount($exp = null)
    {
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'), array('num_product' => 'COUNT(*)'));
        if ($exp) {
			if (isset($exp['frontend_active']) || isset($exp['deleted']) ) {
                $select->joinLeft(array('e' => $this->_prefix.'enterprise'), "p.enterprise_id = e.id", array());
				if (isset($exp['frontend_active']))
					$select->where("e.frontend_active = ?", $exp['frontend_active']);
				if (isset($exp['deleted']))
					$select->where("e.deleted != 1");					   
            }		
            if (isset($exp['strcat_id'])) {
                $select->where("'{$exp['strcat_id']}' LIKE concat('%',p.category_id,'%')");
            }
            if (isset($exp['product_status'])) {
                $select->where('p.product_status = ?', $exp['product_status']);
            }
            if (isset($exp['keyword'])) {
                $select->where("p.product_admin_name LIKE '%".addslashes($exp['keyword'])."%'");
            }
            if (isset($exp['enterprise_id'])) {
                $select->where("p.enterprise_id = ?", $exp['enterprise_id']);
            }
        }
       // echo $select;die;
        $row = $select->query()->fetch();
        return $row->num_product;
    }
    
    public function updateRate($data){
    	$sql = "Update {$this->_prefix}shop_product set 
    			product_price_currency = '{$data['product_price_currency']}', 
    			product_price = product_price * {$data['rate']},
    			product_shipping_price = product_shipping_price * {$data['rate']},
    			product_shipping_price_1 = product_shipping_price_1 * {$data['rate']},
    			product_shipping_price_2 = product_shipping_price_2 * {$data['rate']}
    			where enterprise_id = {$data['enterprise_id']}
    			";    	
    	return $this->_conn->query($sql);    	
    }
}
